import redis


class SensorCache:
    """
    传感器数据，最多保留100条实时数据

    """
    _redis: redis.Redis
    _size: int

    _INSTANCE = None

    def __init__(self, key, size=19):
        self._redis = redis.Redis.from_url('redis://127.0.0.1:6379/2')
        self._size = size
        self.key = key

    def append(self, data):
        self._redis.lpush(self.key, data)
        self._trim()

    def get_all(self):
        return [eval(i) for i in reversed(self._redis.lrange(self.key, 0, -1))]

    def _trim(self):
        self._redis.ltrim(self.key, 0, self._size)
